const { getAdd, setDefAdd } = require("../../../utils/api");

// pages/addresspage/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList: [],
    showDel: false,
    addId: '',
    urlType: '',
    preData: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    this.data.urlType = options.urltype
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAddress()
  },

  onBack() {
    wx.navigateBack({
      delta: 1
    })
  },

  editAddress(e) {
    if (e.currentTarget.dataset.type == 'add') {
      wx.navigateTo({
        url: `/packageA/pages/editaddress/index`,
      });
    } else {
      wx.navigateTo({
        url: `/packageA/pages/editaddress/index?id=${e.currentTarget.dataset.item.id}`,
      });
    }

  },

  //获取地址列表
  getAddress() {
    this.data.addressList = []
    getAdd().then((res) => {
      if (res.errcode == 0) {
        this.setData({
          addressList: res.addresslist
        })
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
        });

      }
    })
  },

  //删除地址
  delAddress(e) {
    this.setData({
      addId: e.currentTarget.dataset.item.id,
      showDel: true,

    })
  },


  //设置默认地址
  toDefault(e) {
    let params = {
      addid: e.currentTarget.dataset.id
    }
    setDefAdd(params).then((res) => {

      if (res.errcode == 0) {
        wx.showToast({
          title: '设置成功',
          icon: 'success',
          success: (result) => {
            setTimeout(() => {
              this.getAddress()
            }, 1000);

          },

        });

      }
    })
  },

  //选择地址
  chooseAdd(e) {
    if (this.data.urlType == 'change') {

      let chooseData = e.currentTarget.dataset.item
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2];
      prevPage.setData({
        "preData.name": chooseData.name,
        "preData.phone": chooseData.phone,
        "preData.address": `${chooseData.province}${chooseData.city}${chooseData.area}${chooseData.address}`,
        "preData.id": chooseData.id
      })

      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        })
      }, 1000);

    } else {
      return
    }


  }
})